package com.atguigu.distributed.lock.leecode;

import java.util.HashMap;
import java.util.Map;

public class LRUTest {
    class Node<K,V>{
        K key;
        V value;
        private Node<K,V> prev;
        private Node<K,V> next;
        public Node(){
            this.prev = this.next = null;
        }
        public Node(K key,V value){
            this.key = key;
            this.value = value;
            this.prev = this.next = null;
        }
    }
    class DoubleLinkedList<K,V>{
        Node<K,V> head;
        Node<K,V> tail;
        public DoubleLinkedList(){
            head = new Node<>();
            tail = new Node<>();
            head.next = null;
            tail.prev = null;
        }
        //添加到头
        public void addHead(Node<K,V> node){
            node.next = head.next;
            node.prev = head;
            head.next.prev = node;
            head.next = node;
        }
        //添加到尾
        public void addTail(Node<K,V> node){
            node.next = tail;
            node.prev = tail.prev;
            tail.prev.next = node;
            tail.prev = node;
        }
        //删除节点
        public void removeNode(Node<K,V> node){
            node.prev.next = node.next;
            node.next.prev = node.prev;
            node.next = null;
            node.prev = null;
        }
        public Node getLast(){
            return tail.prev;
        }
    }
    private int cacheSize;
    Map<Integer,Node<Integer,Integer>> map;
    DoubleLinkedList<Integer,Integer> doubleLinkedList;
    public LRUTest(int size){
        this.cacheSize = size;
        map = new HashMap<>();
        doubleLinkedList = new DoubleLinkedList<>();
    }
    public int get(int key){
        if(!map.containsKey(key)){
            return -1;
        }
        Node<Integer, Integer> node = map.get(key);
        doubleLinkedList.removeNode(node);
        doubleLinkedList.addHead(node);
        return node.value;
    }
    public void put(int key,int value){
        if(map.containsKey(key)){
            Node<Integer, Integer> node = map.get(key);
            node.value = value;
            map.put(key,node);
            doubleLinkedList.removeNode(node);
            doubleLinkedList.addHead(node);
        }else{
            if(map.size() == cacheSize){
                Node last = doubleLinkedList.getLast();
                map.remove(key);
                doubleLinkedList.removeNode(last);
            }
        }
        //才是新增
        Node<Integer, Integer> newNode = new Node<>(key,value);
        newNode.key = key;
        newNode.value = value;
        map.put(key,newNode);
        doubleLinkedList.addHead(newNode);
    }
}
